package com.banban.user.filter;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.banban.user.vo.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "authFilter", urlPatterns = "/app/api/*")
@Order(1)
@Component
public class AuthFilter implements Filter {
    /**
     * 白名单
     */

    @Value("${whiteList}")
    private String whiteListString;

    //需要拦截的地址
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        resp.setHeader("Access-Control-Allow-Headers", "*");
        String url = req.getRequestURI();
        log.info("url:{}", url);
        boolean al = false;//是否白名单
        for (String s : whiteListString.split(",")) {
            if (url.contains(s)) {
                al = true;
                break;
            }
        }

        if (al) {
            chain.doFilter(request, response);
        } else {
            //拦截接口
            //校验登录状态
            boolean login = StpUtil.isLogin();
            if (!login){
                responseResult(resp, DataResult.fail("未登录"));
            }else {
                chain.doFilter(request, response);
            }
        }
    }

    /**
     * responseResult
     *
     * @param response
     * @param result
     */
    private void responseResult(HttpServletResponse response, DataResult result) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(401);
        try {
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException ex) {
            log.error(ex.getMessage());
        }
    }
}